package com.heima.search.listener;

import com.alibaba.fastjson.JSON;
import com.heima.common.constant.ArticleConstants;
import com.heima.search.pojo.SearchArticleVo;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 要使用springboot提供的组件，就要定义为@Component
 */
@Component
@Slf4j
public class addArticle2EsListener {

    @Autowired
    private RestHighLevelClient client;

    @KafkaListener(topics = ArticleConstants.ARTICLE_ES_SYNC_TOPIC)
    public void onMessage(String message){

        log.info("addArticle2EsListener:{}", message);

        SearchArticleVo articleVo = JSON.parseObject(message, SearchArticleVo.class);
        IndexRequest request = new IndexRequest("lead_news").id(articleVo.getId().toString());
        //这里因为message为JSON，所以直接放进去
        request.source(message, XContentType.JSON);
        try {
            client.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            log.error("error saveArticle2Es:{}", e);
        }

    }
}
